.PHONY: all clean clean_obj lib fsimage mgr-mods

TARGET_CC := ${TC_PREFIX}gcc

TARGET_LD ?= ${TC_PREFIX}ld
TARGET_OBJDUMP ?= ${TC_PREFIX}objdump
TARGET_OBJCOPY ?= ${TC_PREFIX}objcopy
TARGET_NM ?= ${TC_PREFIX}nm

LOCAL_CC ?= gcc

MAKE ?= make
RM ?= rm
LN ?= ln

FIND ?= /usr/bin/find
ECHO ?= echo

CCFLAGS	:= -gstabs -I../inc -I../lib -O0 -nostdlib -nostdinc -fno-builtin # -DU_HEAP_DEBUG

LIBGCC	:= $(shell ${TARGET_CC} -print-libgcc-file-name)

SRCFILES:= $(filter-out bin2S.c mk_rkv_data.c,$(shell ${FIND} . -iname "*.c" -or -iname "*.S" | sed -e 's!\./!!g'))
HEADERS := $(shell ${FIND} . -iname "*.h" | sed -e 's!\./!!g')

OBJFILES:= $(addprefix ../target/usr_,$(addsuffix .o,${SRCFILES}))

all: mgr-mods lib ../target/user_image.S

mgr-mods:
	${V}${MAKE} -C ../mgr-mods

../target/usr_%.o: % ${HEADERS}
	@${ECHO} CC $<
	${V}${TARGET_CC} ${CCFLAGS} $< -c -o$@

../target/usr_entry.S.o: entry.S ${HEADERS} ../target/rkv_data.S
	@${ECHO} CC $<
	${V}${TARGET_CC} ${CCFLAGS} $< -c -o$@

../target/rkv_data.S: ../target/rkv_data ../target/bin2S${LOCAL_EXSFX}
	@${ECHO} bin2S $<
	${V}../target/bin2S${LOCAL_EXSFX} $< $@

../target/rkv_data: rkv_list ../target/mk_rkv_data${LOCAL_EXSFX} $(shell cat rkv_list)
	@${ECHO} mk_rkv_data $<
	${V}../target/mk_rkv_data${LOCAL_EXSFX} $< $@

../target/mk_rkv_data${LOCAL_EXSFX}: mk_rkv_data.c
	${V}${LOCAL_CC} $< -o$@

../target/bin2S${LOCAL_EXSFX}: bin2S.c
	${V}${LOCAL_CC} $< -o$@

../target/user_image.S: ../target/user ../target/user.sym ../target/user.asm ../target/bin2S${LOCAL_EXSFX}
	@${ECHO} bin2S $<
	${V}../target/bin2S${LOCAL_EXSFX} $< $@

lib:
	${V}${MAKE} -C ../lib/

../target/user: ${OBJFILES}
	@${ECHO} LD $@
	${V}${TARGET_LD} -N -T user.ld -o $@ ${OBJFILES} ../target/lib_*.o ${LIBGCC}

../target/user.sym: ../target/user
	${V}${TARGET_NM} $< | grep -i " t " | sed "s/ [tT] / /g" > $@

../target/user.asm: ../target/user
	${V}${TARGET_OBJDUMP} -S $< > $@


clean_obj:
	-${V}${RM} ${OBJFILES}

clean: clean_obj
	-${V}${RM} ../target/user.sym
	-${V}${RM} ../target/user.asm
	-${V}${RM} ../target/user
	-${V}${RM} ../target/bin2S
	-${V}${RM} ../target/mk_rkv_data
	-${V}${RM} ../target/ramfs_export
	-${V}${RM} ../target/ramfs_image
	-${V}${RM} ../target/user_image.S
	-${V}${RM} ../target/rkv_data
	-${V}${RM} ../target/rkv_data.S
